package bb.lanxing.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import bb.lanxing.R;
import bb.lanxing.adapter.holder.WorkoutMergeListViewHolder;
import bb.lanxing.mvp.presetner.i.IWorkoutMergeListPresenter;
import java.lang.ref.WeakReference;

public class WorkoutMergeListAdapter extends RecyclerView.Adapter<WorkoutMergeListViewHolder> {
    private IWorkoutMergeListPresenter presenter;
    private WeakReference<ItemTouchHelper> touchHelperRef;

    public WorkoutMergeListAdapter(IWorkoutMergeListPresenter presenter, ItemTouchHelper touchHelper) {
        this.presenter = presenter;
        this.touchHelperRef = new WeakReference<>(touchHelper);
    }

    @Override
    public WorkoutMergeListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new WorkoutMergeListViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_workout_merge_list_content, parent, false));
    }

    @Override
    public void onBindViewHolder(final WorkoutMergeListViewHolder holder, int position) {
        holder.bind(this.presenter.getItem(position));
        holder.getDragView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ItemTouchHelper itemTouchHelper = (ItemTouchHelper) WorkoutMergeListAdapter.this.touchHelperRef.get();
                if (itemTouchHelper == null || WorkoutMergeListAdapter.this.presenter.isDownloading()) {
                    return false;
                }
                itemTouchHelper.startDrag(holder);
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return this.presenter.getItemCount();
    }
}
